package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.AlertDataHandleDto;
import com.zzyl.nursing.dto.AlertDataPageQueryDto;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-25
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param alertData 报警数据
     * @return 报警数据
     */
    /**
     * 分页查询报警数据
     *
     * @param alertDataPageQueryDto
     * @return
     */
    @Override
    public TableDataInfo selectAlertDataList(AlertDataPageQueryDto alertDataPageQueryDto) {
        //获取当前登录人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //构建分页对象
        IPage page = new Page<>(alertDataPageQueryDto.getPageNum(), alertDataPageQueryDto.getPageSize());
        //构建条件构造器
        LambdaQueryWrapper<AlertData> queryWrapper = new LambdaQueryWrapper<AlertData>();
        queryWrapper.eq(AlertData::getUserId, loginUser.getUserId());
        //按照状态查询
        if (ObjectUtil.isNotEmpty(alertDataPageQueryDto.getStatus())) {
            queryWrapper.eq(AlertData::getStatus, alertDataPageQueryDto.getStatus());
        }
        //按照设备名称查询
        if (StringUtils.isNotEmpty(alertDataPageQueryDto.getDeviceName())) {
            queryWrapper.eq(AlertData::getDeviceName, alertDataPageQueryDto.getDeviceName());
        }
        //按照时间查询
        if (ObjectUtil.isNotEmpty(alertDataPageQueryDto.getStartTime()) && ObjectUtil.isNotEmpty(alertDataPageQueryDto.getEndTime())) {
            queryWrapper.between(AlertData::getCreateTime, alertDataPageQueryDto.getStartTime(), alertDataPageQueryDto.getEndTime());
        }

        //按照创建时间倒序排序
        queryWrapper.orderByDesc(AlertData::getCreateTime);
        // 执行查询
        page = page(page, queryWrapper);

        //返回分页对象
        return getTableDataInfo(page);
    }

    @NotNull
    private static TableDataInfo getTableDataInfo(IPage page) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setMsg("请求成功");
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 处理设备报警数据
     *
     * @param alertDataHandleDto
     */
    @Transactional
    @Override
    public boolean handleAlertData(AlertDataHandleDto alertDataHandleDto) {
        //查询报警数据
        AlertData alertData = getById(alertDataHandleDto.getId());
        if (ObjectUtil.isEmpty(alertData) || alertData.getStatus().equals(1)) {
            throw new BaseException("该报警数据已被处理");
        }

        //从当前线程中获取用户数据，更新报警数据
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //获取当前登录人ID
        Long userId = loginUser.getUserId();
        // 获取当前登录人名称
        String username = loginUser.getUsername();
        // 更新报警数据

        //日期时区转换
        LocalDateTime processingTime = alertDataHandleDto.getProcessingTime()
                .atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        LambdaUpdateWrapper<AlertData> alertDataWrapper = new LambdaUpdateWrapper();
        alertDataWrapper.set(AlertData::getProcessingResult, alertDataHandleDto.getProcessingResult())
                .set(AlertData::getProcessingTime, processingTime)
                .set(AlertData::getProcessorName, username)
                .set(AlertData::getUpdateBy, userId)
                .set(AlertData::getStatus, 1)
                .eq(AlertData::getIotId, alertData.getIotId())
                .eq(AlertData::getFunctionId, alertData.getFunctionId())
                .eq(AlertData::getAlertRuleId, alertData.getAlertRuleId());
        return update(alertDataWrapper);

    }

}
